package home

import (
	"fmt"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/text/gregex"
	"github.com/gogf/gf/text/gstr"
	"github.com/gogf/gf/util/gconv"
	"github.com/golang/glog"
	"yunAIYI/app/api/job"
	"yunAIYI/app/middleware"
	"yunAIYI/app/model/ai_history"
	"yunAIYI/app/model/ai_user"
	"yunAIYI/app/util"
)

type LoginUser struct {
	Username string `p:"username"`
	Password string `p:"password"`
}
type UpdateUser struct {
	Phone       string `p:"phone"`
	Password    string `p:"password"`
	LastuseTime string `p:"lastuseTime"`
}

func ShowSesssion(r *ghttp.Request) {
	i := r.Session.Map()
	r.Response.WriteJsonExit(i)
}

func LoginOut(r *ghttp.Request) {
	r.Session.Remove(middleware.SESSIONKEY)

	i := r.Session.Map()

	fmt.Print("i=", i)
	r.Response.WriteTpl("login.html", g.Map{
		"info": "",
	})
}

type LayiUiTable struct {
	Code  int                  `json:"code"`
	Msg   string               `json:"msg"`
	Count int                  `json:"count"`
	Data  []*ai_history.Entity `json:"data"`
}

func PageHistory(r *ghttp.Request) {
	phone := r.Session.GetString(middleware.SESSIONKEY)
	historytype := r.GetString("type")

	glog.Info("phone:", phone)
	var page *job.LayuiPage

	if err := r.Parse(&page); err != nil {
		glog.Error("分页参数转struct异常:", err)
	}

	pageint := page.Page
	limit := page.Limit

	db := g.DB()
	count, _ := db.Table("ai_history").Count()
	var list []*ai_history.Entity
	if gstr.Equal(historytype, "all") && gstr.Equal(phone, "admin") {
		all, _ := db.Table("ai_history").Order("id desc").Limit(limit*(pageint-1), limit).All()
		err := all.Structs(&list)
		if err != nil {
			glog.Error(err)
		}
	} else {
		all, _ := db.Table("ai_history").Where("phone=?", phone).Order("id desc").Limit(limit*(pageint-1), limit).All()
		err := all.Structs(&list)
		if err != nil {
			glog.Error(err)
		}
		//非admin才把历史记录中手机号隐藏
		for i := 0; i < len(list); i++ {
			list[i].UserToPhone = util.HidePhone(list[i].UserToPhone)
		}
	}

	t := LayiUiTable{Count: count, Msg: "", Code: 0, Data: list}
	r.Response.Write(t)
}
func MyHistory(r *ghttp.Request) {
	r.Response.WriteTpl("myhistory.html", g.Map{})
}
func Manager(r *ghttp.Request) {
	r.Response.WriteTpl("history.html", g.Map{})
}
func User(r *ghttp.Request) {
	userName := r.Session.Get(middleware.SESSIONKEY)
	entity, _ := ai_user.FindOne("phone=?", userName)

	method := r.Request.Method
	if method == "GET" {
		r.Response.WriteTpl("user.html", g.Map{
			"Phone":       (entity.Phone),
			"LastuseTime": entity.LastuseTime,
			"Password":    entity.Password,
		})
	} else {

		var user *UpdateUser
		if err := r.Parse(&user); err == nil {
			glog.Info("参数:", user)
			entity, _ := ai_user.FindOne("phone=?", user.Phone)

			entity.Password = user.Password
			entity.Update()
			r.Response.WriteTpl("user.html", g.Map{
				"Phone":       (entity.Phone),
				"LastuseTime": entity.LastuseTime,
				"Password":    entity.Password,
			})
		} else {
			r.Response.Write("error:" + err.Error())
		}
	}
}
func Main(r *ghttp.Request) {
	userName := r.Session.Get(middleware.SESSIONKEY)
	entity, _ := ai_user.FindOne("phone=?", userName)

	r.Response.WriteTpl("home.html", g.Map{
		"Phone":       util.HidePhone(entity.Phone),
		"PhoneAll":    entity.Phone,
		"LastuseTime": entity.LastuseTime,
	})

}
func Login(r *ghttp.Request) {
	method := r.Request.Method
	if method == "GET" {

		//仅当80端口线上正式环境，才自动http跳转https
		//fmt.Println("r.Request.Host=", r.Request.Host)
		if r.Request.TLS == nil && !gstr.ContainsAny(r.Request.Host, ":") {
			r.Response.RedirectTo("https://" + gstr.Replace(r.Request.Host, ":"+gconv.String(util.GetPort()), ""))
		} else {
			r.Response.WriteTpl("login.html", g.Map{
				"info": "",
			})
		}

	} else {
		var login bool = false
		var user *LoginUser
		if err := r.Parse(&user); err == nil {
			glog.Info("参数:", user)

			//电话号码校验
			isphone := gregex.IsMatchString(`^(1[3|4|5|8][0-9]\d{4,8})$`, user.Username)
			if gstr.Equal(user.Username, "admin") {
				isphone = true
			}
			if !isphone {
				login = false
				r.Response.Write(login)
			}
			entity, _ := ai_user.FindOne("phone=?", user.Username)
			if entity != nil {
				//已经存在
				entity, _ = ai_user.Model.Where("phone=?", user.Username).And("password=?", user.Password).One()
				if entity != nil {
					login = true
					entity.LastuseTime = gtime.Now().String()
					entity.Update()
				} else {
					login = false
				}
			} else {
				entity = &ai_user.Entity{
					Phone:        user.Username,
					Password:     user.Username,
					FirstuseTime: gtime.Now().String(),
					LastuseTime:  gtime.Now().String(),
					SmsCount:     10,
				}

				entity.Save()
				login = true
				//首次默认登陆成功
			}

			if login {
				r.Session.Set(middleware.SESSIONKEY, user.Username)
			}
			r.Response.Write(login)
		} else {
			r.Response.Write("error:" + err.Error())
		}
	}

}
